<template>
  <div>
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="ruleForm"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item
        label="名称"
        prop="name"
        :rules="{
          required: true,
          message: '请输入名称',
        }"
      >
        <el-input v-model="ruleForm.name" />
      </el-form-item>

      <el-form-item
        label="图片"
        prop="fileUrl"
        :rules="{
          required: true,
          message: '请上传图片',
          type: 'array',
          max: 1,
        }"
      >
        <el-upload
          ref="uploadRef"
          :limit="1"
          list-type="picture"
          v-model:file-list="ruleForm.fileUrl"
          :http-request="(options) => handleUpload(options, UploadImgPost)"
        >
          <template #trigger>
            <el-button type="primary">选择图片（5mb）</el-button>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="模型"
        prop="modelUrl"
        :rules="{
          required: true,
          message: '请上传模型',
          type: 'array',
          max: 1,
        }"
      >
        <el-upload
          ref="uploadRef"
          :limit="1"
          list-type="text"
          v-model:file-list="ruleForm.modelUrl"
          :http-request="(options) => handleUpload(options, UploadModelPost)"
        >
          <template #trigger>
            <el-button type="primary">选择模型（30mb）</el-button>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="信息"
        prop="mate"
        :rules="{
          required: true,
          message: '请输入信息',
        }"
      >
        <el-input type="textarea" v-model="ruleForm.mate" />
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="submit">{{
      isUpdate ? "更新" : "创建"
    }}</el-button>
  </div>
</template>

<script lang="ts" setup>
import { TrackCratedPost, TrackDetailGet, TrackUpdatePost } from "@/api/track";
import { UploadImgPost, UploadModelPost } from "@/api/upload";
import { FormInstance } from "element-plus";

const ruleForm = ref({
  name: "",
  mate: "",
  fileUrl: [] as any,
  modelUrl: [] as any,
});
const route = useRoute();

const isUpdate = computed(() => route.path === "/track/edit");

onMounted(async () => {
  if (route.query.id) {
    const { data } = await TrackDetailGet(route.query.id);
    ruleForm.value = {
      //@ts-ignore
      id: Number(route.query.id),
      name: data.name,
      mate: data.mate,
      fileUrl: [
        {
          name: "图片",
          url: `http://${data.fileUrl}`,
        },
      ],
      modelUrl: [
        {
          name: "模型",
          url: `http://${data.modelUrl}`,
        },
      ],
    };
  }
});

async function handleUpload(options: any, api: Function) {
  const form = new FormData();
  form.append("file", options.file);
  const data = await api(form);
  return data.url;
}

const formRef = ref<FormInstance>();
function submit() {
  formRef.value?.validate(async (e) => {
    if (e) {
      const data = {
        ...ruleForm.value,
        // @ts-ignore
        fileUrl: ruleForm.value.fileUrl
          //@ts-ignore
          .map((v) => {
            if (typeof v === "string") {
              return v;
            }
            return v.response;
          })
          .at(0),
        // @ts-ignore
        modelUrl: ruleForm.value.modelUrl
          // @ts-ignore
          .map((v) => {
            if (typeof v === "string") {
              return v;
            }
            return v.response;
          })
          .at(0),
      };
      if (isUpdate.value) {
        await TrackUpdatePost(data);
      } else {
        await TrackCratedPost(data);
      }
      ElMessage.success("操作成功");
    }
  });
}
</script>
